import { base64toFile } from "./common.methods";

/**
 * 将图像进行缩放处理，返回缩放后的图像数据
 * @param img 图像元素
 * @param maxWidthOrHeight 最大宽度或高度限制
 * @returns 缩放后的图像数据
 */
export async function ProportionalCompression(img: HTMLImageElement, width: number, height: number, maxWidthOrHeight: number): Promise<File> {
  let scaledWidth, scaledHeight;
  if (width >= height) {
    // 如果宽度大于等于高度，则以宽度为基准缩放
    const scale = maxWidthOrHeight / width;
    scaledWidth = maxWidthOrHeight;
    scaledHeight = height * scale;
  } else {
    // 如果高度大于宽度，则以高度为基准缩放
    const scale = maxWidthOrHeight / height;
    scaledWidth = width * scale;
    scaledHeight = maxWidthOrHeight;
  }
  // 创建缩放后的图像
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  canvas.width = scaledWidth;
  canvas.height = scaledHeight;
  ctx.drawImage(img, 0, 0, width, height, 0, 0, scaledWidth, scaledHeight);

  // 获取缩放后的图像的 base64 数据
  const dataURL = canvas.toDataURL("image/jpeg");
  const file = base64toFile(dataURL);
  return file;
}
